#include "PhoneBookServlet.h"

#include "HttpRequest.h"
#include "HttpResponse.h"


#include <QXmlStreamWriter>
#include <QContactPhoneNumber>
#include <QContactName>
#include <QSystemDeviceInfo>


PhoneBookServlet::PhoneBookServlet(HttpServer *parent)
    : AbstractServlet(parent)
    , m_contactManager(new QContactManager())
{

}

PhoneBookServlet::~PhoneBookServlet()
{

    delete m_contactManager;
}

void PhoneBookServlet::request(HttpRequest *request, HttpResponse *response)
{
    QSystemDeviceInfo info;

    response->setStatusCode(HttpResponse::HttpOK);
    response->setMimeType("text/xml");
    response->sendHeader();
    QXmlStreamWriter stream(response->outputDevice());
    stream.setAutoFormatting(true);
    stream.writeStartDocument();

    stream.writeStartElement("SnomIPPhoneDirectory");

    stream.writeTextElement("Title", QString("%1 %2").arg(info.manufacturer()).arg(info.model()));
    /* Probaly add later:
    <Title>Menu</Title>
    <Prompt>Prompt</Prompt>
    */
    QList<QContact> contacts(m_contactManager->contacts());

    foreach (QContact contact, contacts) {
        stream.writeStartElement("DirectoryEntry");

        QContactName name(contact.detail<QContactName>());

        stream.writeTextElement("Name", QString("%1 %2").arg(name.firstName()).arg(name.lastName()));
        stream.writeTextElement("Telephone", contact.detail<QContactPhoneNumber>().number());

        stream.writeEndElement(); // DirectoryEntry
    }



    stream.writeEndElement(); // SnomIPPhoneDirectory
    stream.writeEndDocument();
}
